#include <iostream>
#include <cstdio>
#include <string.h>
#include <errno.h>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
  pid_t id = fork();
  if(id < 0)
  {
    printf("errno: %d,errstring:%s\n",errno,strerror(errno));
    return errno;
  }
  else if(id == 0)
  {
    //子进程
    int cnt = 5;
    while(cnt)
    {
      printf("子进程运行中，pid:%d\n",getpid());
      cnt--;
      sleep(1);
      //int a = 1/0; 
    }
    //伪造错误信号
    //int *p = nullptr;
    //*p = 100;
    exit(100);
  }
  else
  {
    //sleep(10);
    //pid_t rid = wait(nullptr);
    //pid_t rid = waitpid(-1,nullptr,0); //==wait(nullptr)
    int status = 0;
    pid_t rid = waitpid(id,&status,0);
    if(rid > 0)
    {
      if(WIFEXITED(status))
      {
        printf("wait sub process sucess,rid:%d\n,status:%d\n",rid,WEXITSTATUS(status));
      }
      else{
        printf("child process quit error!");
      }
    }
    while(true)
    {
      printf("我是父进程：pid:%d\n",getpid());
      sleep(2);
    }
  }
    return 0;
}
